package com.mock.action.login;

import java.util.List;
import java.util.Map;

import com.mock.dao.UserDao;
import com.mock.dao.impl.UserDaoImpl;
import com.mock.model.User;
import com.mock.utils.CommonUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4052394121481252001L;

	@Override
	public String execute() throws Exception {

		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get("logged") == "true") {
			return SUCCESS;
		} else {
			UserDao userDao = new UserDaoImpl();
//			userDao.add(new User("admin", CommonUtils.MD5("123456"),
//					"admin@gmail.com", "administrator"));
			List<User> users = userDao.getAllUser();
			if (username == null || "".equalsIgnoreCase(username)) {
				addActionError("Username cannot be null");
				return ERROR;
			}
			if (password == null || "".equalsIgnoreCase(password)) {
				addActionError("Password cannot be null");
				return ERROR;
			}
			for (User user : users) {
				if ((user.getAccount()).equalsIgnoreCase(username)
						&& (user.getPassword()).equalsIgnoreCase(CommonUtils
								.MD5(password))) {
					session.put("logged", "true");
					session.put("username", username);
					session.put("userId", user.getId());
					return SUCCESS;
				}
			}			
						
			addActionError("Wrong username or password");
			return ERROR;
		}
	}

	public String main() {
		return SUCCESS;
	}
	
	public String okAction() {
		return SUCCESS;
	}

	private String username;
	private String password;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
